package com.chainyoung.trademarket.ui;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.MenuItem;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.appcommon.entity.HdWallet;
import com.chainyoung.common.appcommon.entity.HdWalletCache;
import com.chainyoung.common.appcommon.entity.HdWallets;
import com.chainyoung.common.appcommon.entity.TradeParams;
import com.chainyoung.common.appcommon.entity.Version;
import com.chainyoung.common.appcommon.hdwallet.CoinConstant;
import com.chainyoung.common.appcommon.hdwallet.WalletStoreManger;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.base.NullFragment;
import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.bus.AppManagerEvent;
import com.chainyoung.common.bus.RxBus;
import com.chainyoung.common.common_widget.CustomViewPager;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.http.websocket.WebSoketUtils;
import com.chainyoung.common.utils.AppUtils;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.component_tmperson.entity.MyTotalAsset;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.chainyoung.trademarket.R;
import com.chainyoung.common.adpter.BaseFragmentAdapter;
import com.chainyoung.trademarket.di.component.DaggerMainComponent;
import com.chainyoung.trademarket.di.module.MainModule;
import com.chainyoung.trademarket.entity.Ad;
import com.chainyoung.trademarket.mvp.contract.MainContract;
import com.chainyoung.trademarket.mvp.presenter.MainPresenter;
import com.chainyoung.trademarket.utils.BottomNavigationViewHelper;
import com.kenai.jffi.Main;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.ycbjie.ycstatusbarlib.StatusBarUtils;
import cn.ycbjie.ycstatusbarlib.bar.StateAppBar;

import static com.chainyoung.common.appcommon.hdwallet.CoinConstant.ETH;
import static com.chainyoung.common.bus.AppManagerEvent.APP_EXIT;
import static com.chainyoung.common.constant.CommonStringConstants.CURRENCY_IN;
import static com.chainyoung.common.constant.CommonStringConstants.CURRENCY_OUT;
import static com.chainyoung.common.constant.CommonStringConstants.IS_GET_WALLET;
import static com.chainyoung.common.constant.CommonStringConstants.TRADE_NAME;
import static com.chainyoung.common.constant.CommonStringConstants.TRADE_TYPE;
import static com.chainyoung.common.constant.LibConstant.IS_PUT_JPUSH_ALIAS;
import static com.chainyoung.router.RouterConstants.PATH_MAIN_MARKET_ACTIVITY;

@Route(path = PATH_MAIN_MARKET_ACTIVITY)
public class MainMarketActivity extends BaseActivity<MainPresenter> implements MainContract.View {


    @BindView(R.id.view_pager)
    CustomViewPager viewPager;
    @BindView(R.id.navigation)
    BottomNavigationView navigation;

    private static final String TAG = "MainMarketActivity";

    private List<Fragment> fragmentList = new ArrayList<>(4);

    private int page;
    private int tradeType = 0;//TYPE_BUY = 1; TYPE_SELL = 2;
    private String tradeName;//交易对名称

    private boolean isGetWallet;//是否创建或者导入了钱包

    private boolean isPushJpushAlias = false;//是否添加极光推送alias

    /**
     * 本地钱包缓存
     */
    private List<HdWalletCache> walletList = new ArrayList<>();


    /**
     * 交易区
     */
    private String currencyOut;
    /**
     * 要交易的币
     */
    private String currencyIn;


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            setDefaultIcon();
            switch (item.getItemId()) {
                case R.id.navigation_market:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(mContext, R.color.white));
                    }
                   // setWhiteStatusBar();
                    //   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    item.setIcon(R.mipmap.ic_index_pressed);
                    viewPager.setCurrentItem(0, false);
                    return true;
                case R.id.navigation_trade:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(mContext, R.color.white));
                    }
                   // setWhiteStatusBar();
                    //   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    item.setIcon(R.mipmap.ic_bb_trade_pressed);
                    viewPager.setCurrentItem(1, false);

                    return true;
                case R.id.navigation_fiat_currency:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(mContext, R.color.white));
                    }
                    //setWhiteStatusBar();
                    item.setIcon(R.mipmap.ic_fiat_currency_pressed);
                    viewPager.setCurrentItem(2, false);
                    return true;

                case R.id.navigation_purse:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color._4461f5));
                    }
//                    StateAppBar.translucentStatusBar(MainMarketActivity.this,
//                            true);
                    //   setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    item.setIcon(R.mipmap.ic_purse_selected);
                    viewPager.setCurrentItem(3, false);
                    //   ((MineFragment) fragmentList.get(2)).refreshCoin();
                    return true;
                case R.id.navigation_user:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        getWindow().setStatusBarColor(ContextCompat.getColor(mContext, R.color.white));
                    }
                  //  setWhiteStatusBar();
                    item.setIcon(R.mipmap.ic_user_pressed);
                    viewPager.setCurrentItem(4, false);
                    return true;

            }
            return false;
        }
    };

    private void setWhiteStatusBar(){
        StateAppBar.setStatusBarColor(MainMarketActivity.this,
                ContextCompat.getColor(MainMarketActivity.this,
                        R.color.white));
        //状态栏亮色模式，设置状态栏黑色文字、图标
        StatusBarUtils.StatusBarLightMode(MainMarketActivity.this);
    }



    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        page = getIntent().getIntExtra("page", 1);
        currencyOut = getIntent().getStringExtra(CURRENCY_OUT);
        currencyIn = getIntent().getStringExtra(CURRENCY_IN);
        tradeType = getIntent().getIntExtra(TRADE_TYPE, 0);
        tradeName = getIntent().getStringExtra(TRADE_NAME);
        isGetWallet = getIntent().getBooleanExtra(IS_GET_WALLET, false);
        viewPager.setCurrentItem(page, false);
        navigation.setSelectedItemId(getItemId(page));
        if (page == 1 && tradeType != 0) {
            EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.TRADE_TYPE, new TradeParams(tradeType, tradeName)));
        } else if (page == 3 && isGetWallet) {
            EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.IS_GET_NEW_WALLET));
        }

    }

    private void setDefaultIcon() {
        MenuItem market = navigation.getMenu().findItem(R.id.navigation_market);
        market.setIcon(R.mipmap.ic_index_normal);
        MenuItem live = navigation.getMenu().findItem(R.id.navigation_trade);
        live.setIcon(R.mipmap.ic_bb_trade_normal);
        MenuItem voice = navigation.getMenu().findItem(R.id.navigation_fiat_currency);
        voice.setIcon(R.mipmap.ic_fiat_currency_normal);
        MenuItem user = navigation.getMenu().findItem(R.id.navigation_purse);
        user.setIcon(R.mipmap.ic_purse_normal);
        MenuItem find = navigation.getMenu().findItem(R.id.navigation_user);
        find.setIcon(R.mipmap.ic_user_normal);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent.builder()
                .appComponent(appComponent)
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUI() {
        BottomNavigationViewHelper.disableShiftMode(navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        int[][] states = new int[][]{
                new int[]{-android.R.attr.state_checked},
                new int[]{android.R.attr.state_checked}
        };

        int[] colors = new int[]{getResources().getColor(R.color._7e8da6),
                getResources().getColor(R.color._4486f5)
        };
        ColorStateList csl = new ColorStateList(states, colors);
        navigation.setItemTextColor(csl);
        navigation.setItemIconTintList(null);
        page = getIntent().getIntExtra("page", 0);
        initFragments();

        checkUpdate();
        isPushJpushAlias = SPUtil.getBoolean(IS_PUT_JPUSH_ALIAS, false);
        if (!isPushJpushAlias && CommonUtil.getLoginStatus()) {
            setAlias();
        }

    }



    private void initFragments() {
        fragmentList.add(getTargetFragment(RouterConstants.PATH_INDEX));
        fragmentList.add(getTargetFragment(RouterConstants.PATH_TRADE_CURRENCY));
        fragmentList.add(getTargetFragment(RouterConstants.PATH_TRADE_FIAT_CURRENCY));
        fragmentList.add(getTargetFragment(RouterConstants.PATH_MARKET_WALLET));
        fragmentList.add(getTargetFragment(RouterConstants.PATH_USER_CENTER));
        viewPager.setAdapter(new BaseFragmentAdapter(getSupportFragmentManager(), fragmentList));
        viewPager.setOffscreenPageLimit(5);
        viewPager.setCurrentItem(page, false);
        navigation.setSelectedItemId(getItemId(page));
    }

    private int getItemId(int page) {
        switch (page) {
            case 0:
                return R.id.navigation_market;
            case 1:
                return R.id.navigation_trade;
            case 2:
                return R.id.navigation_fiat_currency;
            case 3:
                return R.id.navigation_purse;
            case 4:
                return R.id.navigation_user;
        }
        return R.id.navigation_market;
    }

    private BaseFragment getTargetFragment(String path) {
        BaseFragment fragment = (BaseFragment) (RouterUtils.getInstance()
                .build(path)
                .navigation());

        if (fragment == null) {
            fragment = new NullFragment();
        }
        return fragment;
    }


    @Override
    protected void initData() {
        getUserInfo();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_trade_market;
    }

    //------------------------------------------------------极光推送-----------------------------------------------------------
    private void setAlias() {
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, CommonUtil.getUserInfo().getToken()));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {


        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i(TAG, logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    SPUtil.put(IS_PUT_JPUSH_ALIAS, true);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i(TAG, logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e(TAG, logs);
            }

        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d(TAG, "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
                    Log.i(TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    //------------------------------------------------------网络请求------------------------------------------------------------
    private void getUserInfo() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        mPresenter.getUserInfo(map);
    }

    private void checkUpdate() {
        mPresenter.checkUpdate();
    }

    //------------------------------------------------------本地钱包兼容最初版本，将文件里面的本地钱包存入数据库------------------------------------------------------------

    /**
     * 初始版本只有一个ETH 钱包，如果之前没有存入数据库，则存入
     */
    private void addHdWallet() {

    }

    private void getWallets() {
        mPresenter.getAllHdWalletCaches(null);
    }

    //------------------------------------------------------网络请求返回结果-----------------------------------------------------
    @Override
    public void onGetUserInfoSuccess(UserInfo userInfo) {
        UserInfo data = CommonUtil.getUserInfo();
        userInfo.setIs_setpaypassword(userInfo.getIs_setpaypassword());
        userInfo.setToken(userInfo.getToken());
        userInfo.setH5_chat_url(userInfo.getH5_chat_url());
        userInfo.setChatId(data.getChatId());
        CommonUtil.setUserInfo(userInfo);
    }

    @Override
    public void showVersion(final Version data) {
        if (data == null || data.getVersion_code() <= AppUtils.getAppVersionCode(mContext)) {
            return;
        } else if (data.getVersion_code() > AppUtils.getAppVersionCode(mContext)) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    RouterUtils.getInstance()
                            .build(RouterConstants.PATH_UPDATE)
                            .withParcelable(LibConstant.VERSION, data)
                            .navigation(mContext);
                }
            }, 0);
        }
    }

    //------------------------------------------------------数据库返回结果-----------------------------------------------------

    /**
     * @param data
     */
    @Override
    public void onAddHdWalletCacheSuccess(HdWalletCache data) {

    }

    /**
     * 兼容初始版本本地钱包,将其加入数据库
     *
     * @param datas
     */
    @Override
    public void onGetAllHdWalletCaches(List<HdWalletCache> datas) {
        walletList.clear();
        if (datas != null) {
            walletList.addAll(datas);
        }
        HdWallets hdWallets = WalletStoreManger.getHdWallets();
        HdWallet hdWallet = null;
        try {
            hdWallet = hdWallets.getWallets().get(0).getWallets().get(0);
        } catch (Exception ignored) {

        }
        if (hdWallet != null) {
            boolean isNeedAdd = true;
            if (!walletList.isEmpty()) {
                for (HdWalletCache item : walletList) {
                    if (item.getAddress().equals(hdWallet.getAddress())) {
                        isNeedAdd = false;
                        return;
                    } else {
                        isNeedAdd = true;
                    }
                }
            }
            if (isNeedAdd) {
                HdWalletCache hdWalletCache = new HdWalletCache();
                hdWalletCache.setCoinType(hdWallet.getCoinType());
                hdWalletCache.setAddress(hdWallet.getAddress());
                hdWalletCache.setMnemonic(hdWallet.getMnemonic());
                hdWalletCache.setPrivateKey(hdWallet.getPrivateKey());
                hdWalletCache.setPublicKey(hdWallet.getPublicKey());
                int num = walletList.size() + 1;
                hdWalletCache.setWalletName(hdWallet.getCoinType() + "-" + num);
                switch (hdWallet.getCoinType()) {
                    case ETH:
                        hdWalletCache.setCnName(CoinConstant.ETH_CNNAME);
                        hdWalletCache.setLogo(com.chainyoung.common.R.mipmap.icon_eth);
                        break;
                }
                mPresenter.addHdWalletCache(hdWalletCache);
            }
        }
    }


//    @Override
//    public void onGetTotalAsset(MyTotalAsset data) {
//
//    }


    @Override
    protected void onResume() {
        super.onResume();
        //WebSoketUtils.getWsManager();

        getWallets();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WebSoketUtils.setWsManagerNull();
    }

    @Override
    public void onBackPressed() {
        exitBy2Click();
    }


    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit;
        if (!isExit) {
            isExit = true; // 准备退出
            ToastUtil.showToast(getString(R.string.press_again_and_exit));
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            RxBus.getDefault().post(new AppManagerEvent(APP_EXIT, getString(R.string.exit_app)));
        }
    }


}
